/**
Workerman Net Client
内网穿透客户端
*/
<?php
use Workerman\Worker;
use Channel\Server;
use Channel\Client;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
require_once __DIR__ . '/../vendor/autoload.php';


$worker = new Worker();

$worker->onWorkerStart = function($worker)
{
    $config = [
        //服务端地址
        'ServerTcp'          =>   "www.wlot.top",
        //服务端端口
        'ServerTcpProt'      =>   2206,
        //自定义域名（域名需要绑定服务器IP/cname解析）
        'Domain'             =>   "cichenman.wkmnet.wlot.top",
        //本地地址
        'LocaHost'           =>   "192.168.1.5",
        //本地端口
        'LocaHostProt'       =>   9701
    ];
   
    echo PHP_EOL.PHP_EOL.PHP_EOL;
    echo "--------------------【NetServer Workerman For PHP】---------------------------".PHP_EOL;
    echo"访问地址：http://".$config['Domain'].":3000/".PHP_EOL;
    echo"本地IP：".$config['LocaHost'].PHP_EOL;
    echo"端口号：".$config['LocaHostProt'].PHP_EOL;
    echo "--------------------【CiChenMan 1570442495@qq.com】-------------------------".PHP_EOL;
   
    // Channel客户端连接到Channel服务端
    Client::connect($config['ServerTcp'], $config['ServerTcpProt']);
    
    //【穿透客户端发送数据给用户】
    // 订阅OnSendMsgToUser事件，并注册事件回调$config['Domain']
    Client::on($config['Domain'], function($event_data)use($config){
        
        //收到广播建立本地的http请求
        // 不支持直接指定http，但是可以用tcp模拟http协议发送数据
        $connection_to_baidu = new AsyncTcpConnection("tcp://".$config['LocaHost'].":".$config['LocaHostProt']);
        
        // 当连接建立成功时，发送http请求数据
        $connection_to_baidu->onConnect = function(AsyncTcpConnection $connection_to_baidu)use($event_data)
        {
            echo "Start - 开始请求".$event_data['user']." - ";
            //发送数据
            $connection_to_baidu->send($event_data['body']);
        };
        
        $connection_to_baidu->onMessage = function(AsyncTcpConnection $connection_to_baidu, $http_buffer)use($event_data)
        {
            //echo $http_buffer;
            echo "拿到数据".$event_data['user']." - ";
            $event_data['body'] = $http_buffer;
            //最后返回数据
            echo "推送数据".$event_data['user']." - ";
            Client::publish("OnSendMsgToUser", $event_data);
            //关闭异步连接
            echo "请求完毕".$event_data['user']." - End".PHP_EOL;
            //$connection_to_baidu->close();
        };

        $connection_to_baidu->onClose = function(AsyncTcpConnection $connection_to_baidu)
        {
            // echo "connection closed\n";
        };
        $connection_to_baidu->onError = function(AsyncTcpConnection $connection_to_baidu, $code, $msg)
        {
            // echo "Error code:$code msg:$msg\n";
        };
        $connection_to_baidu->connect();;
            
    });
    
};

// 运行worker
Worker::runAll();